package cn.itsource.mq._04_direct;
import cn.itsource.mq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
 * @description: 消费者
 */
public class Consumer1 {
    public static final String QUEUE_DIRECT_1 = "queue_direct_1";
    //队列名称
    public static final String EXCHANGE_DIRECT = "exchange_direct";
    /**
     * 步骤：
     * 1、创建连接
     * 2、创建信道
     * 3、创建队列
     * 4、绑定队列到交换机
     * 5、监听队列
     * 6、处理消息
     */
    public static void main(String[] args) throws Exception {
        //1、创建连接
        Connection connection = ConnectionUtil.getConnection();
        //2、创建信道
        Channel channel = connection.createChannel();
        //设置消息并发处理数量
        channel.basicQos(1);
        //3、创建队列
        channel.queueDeclare(QUEUE_DIRECT_1, true, false, false, null);
        //4、绑定队列到交换机
        channel.queueBind(QUEUE_DIRECT_1, EXCHANGE_DIRECT, "error");
        channel.queueBind(QUEUE_DIRECT_1, EXCHANGE_DIRECT, "info");
        //5、监听队列
        channel.basicConsume(QUEUE_DIRECT_1, false, new DefaultConsumer(channel){
            //6、处理消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我是消费者Consumer1，收到消息：" + new String(body));
                //手动签收
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}